/**
 * 
 */
package info.touret.winecellar.bottle.client;

import info.touret.winecellar.bottle.shared.BottleProxy;
import info.touret.winecellar.producer.client.ProducerRequest;
import info.touret.winecellar.producer.client.ProducerRequestFactory;
import info.touret.winecellar.producer.shared.ProducerProxy;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;

import com.google.gwt.activity.shared.Activity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.web.bindery.requestfactory.shared.EntityProxyChange;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.ServerFailure;

/**
 * Widget affichant un formulaire de saisie de bouteille
 * 
 * @author touret-a
 */
public class BottleUI extends Composite implements
		EntityProxyChange.Handler<BottleProxy>, Activity {

	private static BottleUIUiBinder uiBinder = GWT
			.create(BottleUIUiBinder.class);

	interface BottleUIUiBinder extends UiBinder<Widget, BottleUI> {
	}

	/**
	 * Constructeur par defaut --> a ne pas utiliser
	 */
	public BottleUI() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	/**
	 * Constructeur a utiliser
	 * 
	 * @param factory
	 *            qui doit etre initialise avant l appel
	 * @param producerrequestfactory
	 *            factory des Producteurs qui doit etre initialise ( initialize
	 *            event bus ) avant
	 */

	public BottleUI(BottleRequestFactory factory,
			ProducerRequestFactory producerrequestfactory) {
		this();
		bottlerequestFactory = factory;
		this.producerrequestFactory = producerrequestfactory;
		//
		// Initialise la liste des combo box
		populateProducerList();
		populateVintageList();
	}

	@UiField(provided = true)
	Button submitbutton = new Button();

	@UiField(provided = true)
	TextBox name = new TextBox();

	@UiField(provided = true)
	ListBox producername = new ListBox();

	@UiField(provided = true)
	TextBox quantity = new TextBox();

	@UiField(provided = true)
	DateBox toDrink = new DateBox();

	@UiField(provided = true)
	ListBox vintage = new ListBox();

	@UiField(provided = true)
	TextBox denomination = new TextBox();

	private BottleRequestFactory bottlerequestFactory;

	private ProducerRequestFactory producerrequestFactory;

	@Override
	public String mayStop() {
		return null;
	}

	@Override
	public void onCancel() {

	}

	@Override
	public void onStop() {

	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		// TODO Auto-generated method stub

	}

	/**
	 * Initialise la liste des annees
	 */
	@SuppressWarnings("deprecation")
	private void populateVintageList() {
		Integer currentyear = new Date().getYear() + 1900;
		for (int i = currentyear; i > currentyear - 40; i--) {
			vintage.addItem(String.valueOf(i));
		}
	}

	@Override
	public void onProxyChange(EntityProxyChange<BottleProxy> event) {

	}

	private Receiver<List<ProducerProxy>> lastDataProducerReceiver;

	private List<ProducerProxy> lastProducersData;

	/**
	 * Cree une liste de producteurs
	 */
	private void populateProducerList() {

		try {
			ProducerRequest requestProducers = producerrequestFactory
					.producerRequest();

			Request<List<ProducerProxy>> getReq = requestProducers
					.findAllProducers();
			lastDataProducerReceiver = new Receiver<List<ProducerProxy>>() {
				@Override
				public void onSuccess(List<ProducerProxy> response) {
					lastProducersData = new ArrayList<ProducerProxy>(response);
					for (ProducerProxy current : response) {
						producername.addItem(current.getName(), current.getId()
								.toString());
					}
				}

				@Override
				public void onFailure(ServerFailure error) {
					super.onFailure(error);
					Window.alert("Une erreur est surveune :-(");
				}
			};
			getReq.fire(lastDataProducerReceiver);
		} catch (Exception e) {
			// TODO LOGG
			e.printStackTrace();
		}

	}

	/**
	 * MAJ les informations de la bouteille
	 * 
	 * @param event
	 */
	@UiHandler("submitbutton")
	void onSubmitbuttonClick(ClickEvent event) {
		BottleRequest bottlerequest = bottlerequestFactory.bottleRequest();
		BottleProxy proxy = bottlerequest.create(BottleProxy.class);
		proxy.setVintage(Integer.parseInt(vintage.getValue(vintage
				.getSelectedIndex())));
		proxy.setName(name.getText());
		// ajout regle validation
		proxy.setQuantity(Long.parseLong(quantity.getText().equals("") ? "-1"
				: quantity.getText()));
		proxy.setToDrink(toDrink.getValue());
		proxy.setDenomination(denomination.getValue());
		proxy.setAcquired(acquired.getValue());
		if (producername.getSelectedIndex() >= 0) {
			proxy.setProducerID(Long.parseLong(producername
					.getValue(producername.getSelectedIndex())));
		}
		bottlerequest.persist().using(proxy).fire(new Receiver<Void>() {
			@Override
			public void onSuccess(Void response) {
				Window.alert("Insertion OK");
				clearform();
			}

			@Override
			public void onFailure(ServerFailure error) {
				// TODO Auto-generated method stub
				super.onFailure(error);
				GWT.log(error.getMessage());
			}
		});
	}

	@UiField
	DateBox acquired;

	@UiHandler("rollbackbutton")
	void onRollbackbuttonClick(ClickEvent event) {
		clearform();
	}

	/**
	 * Vide le formulaire
	 */
	private void clearform() {
		name.setText("");
		// producername.setTabIndex(1)
		toDrink.setValue(null);
		acquired.setValue(null);
		quantity.setValue("");
		denomination.setValue(null);
	}
}
